from pickle import load, dump
from copy import deepcopy

from Event import *

def loadHistory(filename):
    f = open(filename, "rb") 
    history = load(f)
    f.close()
    return history

class History:
    def __init__(self):
        self.events = []

    def add(self, state, time):
        e = Event(deepcopy(state), time)
        self.events.append(e)
        
    def save(self, filename):
        print "History: Saved to file " + filename + ". " + str(len(self.events)) + " events."
        f = open(filename, "wb") 
        dump(self, f)
        f.close()
        
    def getState(self, time):
        event = None
        for e in self.events:
            if time <= e.time:
                event = e
                break
        if math.fabs(time - event.time) < 1e-6:
            return event.state
        else:
            print "History: TODO Must interpolate"
            print time, event.time
            exit
        
    def printMe(self):
        for e in self.events:
            print "History: {0} @ {1}".format(e.state, e.time)